package com.bnz.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * mybatis访问数据库的工具类
 */
public class MyBatisUtil {
    //1. 获取sqlSessionFactory
    private static SqlSessionFactory getSqlSessionFactory() throws IOException {
        String resource = "mybatis/mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        return sqlSessionFactory;
    }

    //2. 得到SqlSession对象
    public static SqlSession getSqlSession(boolean isAutoCommint) {
        try {
            //2.1 得到sqlSessionFacotry对象
            SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
            //2.2 得到sqlSession对象
            return sqlSessionFactory.openSession(isAutoCommint);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
